//
//  EnterDetailViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/19.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "EnterDetailViewController.h"
#import "DataAnalysis.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "EnterDetailTableViewCell.h"
#import "EnterDetailOneTableViewCell.h"
#import "EnterTableViewTwoCell.h"
#import "TravetTourDetailsViewController.h"
#import "EnterOnlyImageTableViewCell.h"
#import "UMSocial.h"

#import "CoreDatamanager.h"
#import "YJCollection.h"
@interface EnterDetailViewController ()<UITableViewDataSource, UITableViewDelegate, EnterDetailDelegate, EnterDetailOneDelegate>

@property(nonatomic, retain) UIView *titleView;

@property(nonatomic, retain) UIImageView *imageview;

@property(nonatomic, retain) UIImageView *image;

@property(nonatomic, retain) UILabel *titleLabel;

@property(nonatomic, retain) UILabel *detailLabel;

@property(nonatomic, retain) UITableView *tableView;

@property(nonatomic, retain) NSDictionary *enterDic;

@property(nonatomic, retain) NSMutableArray *rowArray;

@property(nonatomic, retain) NSMutableArray *allArray;

@property(nonatomic, retain) NSMutableArray *alladdress;

@property(nonatomic, retain) NSMutableArray *allID;

@property (nonatomic, retain) CoreDatamanager *coreDataManager;

@property (nonatomic, retain) NSArray *coreArray;

@property (nonatomic, retain) NSArray *array;

@property (nonatomic, retain) NSArray *resultArray;

@property(nonatomic, retain) UILabel *nameLabel;

@end

@implementation EnterDetailViewController

- (void)dealloc
{
    [_coreArray release];
    [_array release];
    [_resultArray release];
    [_titleView release];
    [_enterModel release];
    [_imageview release];
    [_image release];
    [_titleLabel release];
    [_detailLabel release];
    [_tableView release];
    [_enterDic release];
    [_rowArray release];
    [_alladdress release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.coreDataManager = [CoreDatamanager shareManager];
    
    self.rowArray = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    self.alladdress = [NSMutableArray array];
    self.allID = [NSMutableArray array];
    
    //解析数据
    [self loadData];
    
    //创建tableView
    [self createTableView];
    
    //创建标题
    [self createTitle];
}

#pragma mark 创建标题
-(void)createTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,kHeight * 64)];
    self.titleView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.0];
    [self.view addSubview:self.titleView];
    [self.titleView release];
    [_titleView release];
    
    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 100 * kWidth, self.titleView.frame.size.height / 2 - 10 * kHeight, kWidth * 200, kHeight * 30)];
    self.nameLabel.text = self.enterModel.name;
    self.nameLabel.textColor = [[UIColor whiteColor]colorWithAlphaComponent:0];
    self.nameLabel.font = [UIFont systemFontOfSize:17 * kWidth];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.titleView addSubview:self.nameLabel];
    [_nameLabel release];

    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(15 * kWidth, 25 * kHeight, 20 * kWidth, 20 * kHeight);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"Food_back"] forState:UIControlStateNormal];
    [self.titleView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //进行判断(是否被收藏)
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"YJCollection"];
    self.coreArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    BOOL result = NO;
    if (_coreArray.count > 0) {
        
        
        for (YJCollection *YJ in self.coreArray) {
            if ([YJ.yjID isEqualToString:[NSString stringWithFormat:@"%@",self.enterModel.ID]]) {
                result = YES;
            }
        }
        if (result == YES) {
            self.array = @[ @"collected", @"fenxiang"];
        }else{
            
            self.array = @[ @"collec", @"fenxiang"];
        }
        
        
    }else{
        
        self.array = @[ @"collec", @"fenxiang"];
        
    }

    for (int i = 0; i < 2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(295 * kWidth + i * 40 * kWidth, 25 * kHeight, 20 * kWidth, 20 * kHeight);
        [btn setBackgroundImage:[UIImage imageNamed:self.array[i]] forState:UIControlStateNormal];
        [self.titleView addSubview:btn];
        btn.tag = 5000 + i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}

-(void)BackAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}

//分享等按钮的点击事件
-(void)btnAction:(UIButton *)btn
{
   if (btn.tag == 5000)
    {
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"YJCollection"];
        self.resultArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        if (self.resultArray.count == 0) {
            YJCollection *yj = [NSEntityDescription insertNewObjectForEntityForName:@"YJCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
            yj.yjID = [NSString stringWithFormat:@"%@",self.enterModel.ID];
            yj.yjName = self.enterModel.name;
            yj.yjURL = self.enterModel.front_cover_photo_url;
            [_coreDataManager saveContext];
            [btn setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        }else{
            BOOL add = NO;
            int index = 0;
            for (int i = 0 ;i < self.resultArray.count; i++){
                
                if ([[self.resultArray[i] yjID] isEqualToString:[NSString stringWithFormat:@"%@",self.enterModel.ID]]) {
                    add = YES;
                    index = i;
                }
                
            }
            
            if (add) {
                [btn setImage:[UIImage imageNamed:@"collec"] forState:UIControlStateNormal];
                [_coreDataManager.managedObjectContext deleteObject:self.resultArray[index]];
                [_coreDataManager saveContext];
            }else{
                YJCollection *yj = [NSEntityDescription insertNewObjectForEntityForName:@"YJCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
                yj.yjID = [NSString stringWithFormat:@"%@",self.enterModel.ID];
                yj.yjName = self.enterModel.name;
                yj.yjURL = self.enterModel.front_cover_photo_url;
                [btn setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
                [_coreDataManager saveContext];
                
            }
            
        }

    }
    else
    {
//        NSLog(@"分享");
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5655ae58e0f55a464d000a1c"
                                          shareText:self.enterModel.name
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                           delegate:nil];

    }
}

#pragma mark 解析数据
-(void)loadData
{
   [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json", self.enterModel.ID]parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
       
       self.enterDic = responseObject;

       for (NSMutableDictionary *dic in [self.enterDic objectForKey:@"trip_days"] ) {
           NSInteger count = 0;
           NSMutableArray *firArray = [NSMutableArray array];
           NSMutableArray *addrressArray = [NSMutableArray array];
           NSMutableArray *idArray = [NSMutableArray array];
           for (NSDictionary *dic1 in [dic objectForKey:@"nodes"]) {
               count = count + [[dic1 objectForKey:@"notes"] count];
               
               for (NSDictionary *dic2 in [dic1 objectForKey:@"notes"]) {
                   [addrressArray addObject:[dic1 objectForKey:@"entry_name"]];
                   [idArray addObject:[dic1 objectForKey:@"entry_id"]];
                   [firArray addObject:dic2];
               }
           }
           
           [self.alladdress addObject:addrressArray];
           [self.allID addObject:idArray];
           [self.allArray addObject:firArray];
           
           [self.rowArray addObject:[NSNumber numberWithInteger:count]];
       }

       [self.tableView reloadData];
       
   } failureBlock:^(NSError *error) {
       NSLog(@"error :%@", error);
   }];
}

#pragma mark 创建tableView
-(void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -20 * kHeight - (1 - kHeight) * 20, self.view.frame.size.width, self.view.frame.size.height + 20 * kHeight - (1 - kHeight) * 20) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[EnterDetailTableViewCell class] forCellReuseIdentifier:@"EnterDetailTableViewCell"];
    [self.tableView registerClass:[EnterDetailOneTableViewCell class] forCellReuseIdentifier:@"EnterDetailOneTableViewCell"];
    [self.tableView registerClass:[EnterTableViewTwoCell class] forCellReuseIdentifier:@"EnterTableViewTwoCell"];

}

//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.rowArray[section] integerValue];
}

//返回分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.enterDic objectForKey:@"trip_days"] count];
}

//返回重用池
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.allArray[indexPath.section][indexPath.row] allKeys] containsObject:@"photo"]) {
        
        if([self.alladdress[indexPath.section][indexPath.row] isKindOfClass:[NSNull class]])
        {
            EnterOnlyImageTableViewCell *cell = [[EnterOnlyImageTableViewCell alloc]init];
            cell.imageName = [[self.allArray[indexPath.section][indexPath.row] objectForKey:@"photo"] objectForKey:@"url"];
            return cell;
        }
        else
        {
            EnterDetailOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnterDetailOneTableViewCell" forIndexPath:indexPath];
            cell.delegate = self;
            cell.imageName = [[self.allArray[indexPath.section][indexPath.row] objectForKey:@"photo"] objectForKey:@"url"];
            if (![self.alladdress[indexPath.section][indexPath.row] isKindOfClass:[NSNull class]]) {
                cell.location = self.alladdress[indexPath.section][indexPath.row];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.ID = self.allID[indexPath.section][indexPath.row];
             return cell;
        }
       
    }
    else
    {
        if ([self.alladdress[indexPath.section][indexPath.row] isKindOfClass:[NSNull class]])
        {
            EnterTableViewTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnterTableViewTwoCell" forIndexPath:indexPath];
            cell.decribe = [self.allArray[indexPath.section][indexPath.row] objectForKey:@"description"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            return cell;
        }
        else
        {
            EnterDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnterDetailTableViewCell" forIndexPath:indexPath];
            cell.delegate = self;
            cell.decribe = [self.allArray[indexPath.section][indexPath.row] objectForKey:@"description"];
            cell.location = self.alladdress[indexPath.section][indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.ID = self.allID[indexPath.section][indexPath.row];;
            return cell;
        }
    }
}

#pragma mark 代理方法
-(void)sendToTravetTourDetailsViewController:(NSNumber *)ID
{
    TravetTourDetailsViewController *travel = [[TravetTourDetailsViewController alloc]init];
    travel.idNumber = ID;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:travel animated:YES];
}

-(void)sendONEToTravetTourDetailsViewController:(NSNumber *)ID
{
    TravetTourDetailsViewController *travel = [[TravetTourDetailsViewController alloc]init];
    travel.idNumber = ID;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:travel animated:YES];
}

//返回行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.allArray[indexPath.section][indexPath.row] allKeys] containsObject:@"photo"]) {
        if([self.alladdress[indexPath.section][indexPath.row] isKindOfClass:[NSNull class]])
        {
            return 200 * kHeight;
        }
        else
        {
          return 225 * kHeight;
        }
        
    }
    else
    {
        if ([self.alladdress[indexPath.section][indexPath.row] isKindOfClass:[NSNull class]]) {
             CGFloat height = [EnterTableViewTwoCell heightOfLabel:[self.allArray[indexPath.section][indexPath.row] objectForKey:@"description"] andTextFont:[UIFont systemFontOfSize:15] andTextWidth: self.view.frame.size.width - 20 * kWidth];
            return height + 10;
        }
        else
        {
            CGFloat height = [EnterTableViewTwoCell heightOfLabel:[self.allArray[indexPath.section][indexPath.row] objectForKey:@"description"] andTextFont:[UIFont systemFontOfSize:15 * kWidth] andTextWidth:self.view.frame.size.width - 20 * kWidth];
           return 30 + height;
        }
        
    }
}

//返回头视图高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 250 * kHeight;
    }
    else
    {
       return 40 * kHeight;
    }
}

//返回尾视图高
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

//返回头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 * kHeight)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 210 * kHeight, self.view.frame.size.width, 40 * kHeight)];
        label.font = [UIFont systemFontOfSize:17 * kWidth];
        label.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
        if ([[[self.enterDic objectForKey:@"trip_days"][section] objectForKey:@"trip_date"] isKindOfClass:[NSNull class]]) {
            label.text = [NSString stringWithFormat:@"DAY%ld",section + 1];
        }
        else
        {
            label.text = [NSString stringWithFormat:@"DAY%ld %@",section + 1, [[self.enterDic objectForKey:@"trip_days"][section] objectForKey:@"trip_date"]];
        }
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
        
        [self createTitleView:view];
        
        return [view autorelease];
    }
    else
    {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40 * kHeight)];
        label.font = [UIFont systemFontOfSize:17 * kWidth];
        label.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
        if ([[[self.enterDic objectForKey:@"trip_days"][section] objectForKey:@"trip_date"] isKindOfClass:[NSNull class]]) {
            label.text = [NSString stringWithFormat:@"DAY%ld",section + 1];
        }
        else
        {
            label.text = [NSString stringWithFormat:@"DAY%ld %@",section + 1, [[self.enterDic objectForKey:@"trip_days"][section] objectForKey:@"trip_date"]];
        }

        label.textAlignment = NSTextAlignmentCenter;
        return [label autorelease];
    }
}

#pragma mark 创建头视图
-(void)createTitleView:(UIView *)view
{
    self.imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0 * kHeight , self.view.frame.size.width, 210 * kHeight)];
    [self.imageview sd_setImageWithURL:[NSURL URLWithString:[self.enterDic objectForKey:@"front_cover_photo_url"]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    [view addSubview:self.imageview];
    [_imageview release];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60 * kWidth, 160 * kHeight, self.view.frame.size.width - 50 * kWidth, 20 * kHeight)];
    self.titleLabel.text = [self.enterDic objectForKey:@"name"];
    self.titleLabel.font = [UIFont systemFontOfSize:16 * kWidth];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.shadowColor = [UIColor colorWithWhite:0.185 alpha:1.000];
    [view addSubview:self.titleLabel];
    [_titleLabel release];
    
    self.detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(60 * kWidth, 180 * kHeight, self.titleLabel.frame.size.width, 20 * kHeight)];
    self.detailLabel.text = [NSString stringWithFormat:@"%@/%@天/%@图", [self.enterDic objectForKey:@"start_date"], [self.enterDic objectForKey:@"days"], [self.enterDic objectForKey:@"photos_count"]];
    self.detailLabel.font = [UIFont systemFontOfSize:13 * kWidth];
    self.detailLabel.textColor = [UIColor colorWithWhite:0.953 alpha:1.000];
    [view addSubview:self.detailLabel];
    [_detailLabel release];
    
    self.image = [[UIImageView alloc]initWithFrame:CGRectMake(10 * kWidth, 160 * kHeight, 40 * kWidth, 40 * kWidth)];
    [self.image sd_setImageWithURL:[NSURL URLWithString:[[self.enterDic objectForKey:@"user"] objectForKey:@"image"]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    self.image.layer.masksToBounds = YES;
    self.image.layer.cornerRadius = kWidth * 20;
    self.image.layer.borderWidth = 2;
    self.image.layer.borderColor = [UIColor whiteColor].CGColor;
    [view addSubview:self.image];
    [_image release];
}

//当滚动时
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > -45 && scrollView.contentOffset.y < 800) {
        self.titleView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:scrollView.contentOffset.y / 800];
    }
    
    self.nameLabel.textColor = [[UIColor whiteColor]colorWithAlphaComponent:scrollView.contentOffset.y];
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}



@end
